package cmd

import (
	"log"
	"os"

	"github.com/spf13/cobra"
	"github.com/spf13/viper"
	"pets.ser163.cn/config"
)

var rootCmd = &cobra.Command{
	Use:   "pets",
	Short: "pets online ...",
}

func Execute() {
	if err := rootCmd.Execute(); err != nil {
		log.Fatalf("Error executing root command: %v", err)
	}
}

func init() {
	cobra.OnInitialize(initConfig)
	rootCmd.PersistentFlags().StringP("config", "c", "config.yaml", "config file")
	viper.BindPFlag("config", rootCmd.PersistentFlags().Lookup("config"))
}

func initConfig() {
	configFile := viper.GetString("config")
	if configFile == "" {
		// 查找配置
		viper.SetConfigName("config")
		viper.SetConfigType("yaml")
		viper.AddConfigPath(".")
		viper.AddConfigPath("./config")
	} else {
		viper.SetConfigFile(configFile)
	}

	if err := viper.ReadInConfig(); err != nil {
		log.Fatalf("Error reading config file: %v", err)
	}

	err := viper.Unmarshal(&config.ConfigInstance)
	if err != nil {
		log.Fatalf("Unable to decode into struct, %v", err)
	}

	// 加载日志
	config.InitLogger()

	// 加载redis配置
	config.InitRedis()

	if len(os.Args) > 1 {
		command := os.Args[1]
		switch command {
		case serveCmd.Name():
			// 只有server模式才加载队列客户端
			// 加载队列配置
			config.InitQueue()
		case queueCmd.Name():
			log.Println("User executed queueCmd")
		case migrateCmd.Name():
			log.Println("User executed migrateCmd")
		case genCmd.Name():
			log.Println("User executed genCmd")
		default:
			log.Println("Unknown command:", command)
		}
	}

}
